<?php

namespace App\Http\Controllers;

use App\Interfaces\SmsService;
use App\Interfaces\UserInterface;
use App\User;
use App\UserMoneyLog;
use App\UserTeam;
use App\UserWithdraw;
use GuzzleHttp\Client;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class MyTeamController extends Controller
{
    protected $user;



    /**
     * 我的团队首页
     */
    public function index(UserInterface $userService){
        $user=User::find(\Auth::id());

        //累计销售额
        $withdrawCount=UserWithdraw::where('user_id',$user->id)->count('id');
        //我的朋友数量

        $myFriendNumber= $userService->getMyFriendNumber($user);
        return view('mobile.myTeam.index',compact('user','withdrawCount','myFriendNumber'));
    }
    /**
     * 提现页面
     */
    public function withdraw(){
        $user=\Auth::user();
        //取出最近的提现信息
        $userWithdraw= UserWithdraw::where('user_id',$user->id)->orderBy('created_at','desc')->first();
        return view('mobile.myTeam.withdraw',compact('user','userWithdraw'));
    }

    /**
     * 提现请求
     * @param Request $request
     */
    public function withdrawStore(Request $request,SmsService $sms){
        //dd($request->all());
        $phone = $request->input('phone');
        $mesCode = $request->input('mesCode');
        $user=\Auth::user();
        $return=['code'=>0,'message'=>''];
        $validator=\Validator::make($request->all(),
            [
                'price'=>'required|numeric',
                'bank_code'=>'required',
                'user_name'=>'required',
                'phone'=>'required',
                'mesCode'=>'required',

            ],[
                    'price.required'=>'请输入提现金额',
                    'bank_code.required'=>'请输入银行卡号',
                    'price.numeric'=>'提现金额格式不正确',
                    'user_name.required'=>'请输入姓名',
                    'phone.required'=>'请填写手机号',
                    'mesCode'=>'请输入验证码',
                 ]
        );
        if ($validator->fails()) {
            $error = $validator->errors();
            foreach ($error->all() as $message) {
                $return['message'] = $message;
                return Response()->json($return);
            }
        }
        if(!$sms->validateRegCode(Session::get('MsgCode_id'),$mesCode)){
            return response()->json(['code'=>0,'message'=>'手机验证码不正确或验证码已过期']);
        }
        if($request->price <50){
            return Response()->json(['code'=>0,'message'=>'提现金额需要大于50']);
        }
        //判断是否有正在申请的提现记录
      $userWithdraw=  UserWithdraw::where('user_id',$user->id)->where('status',UserWithdraw::STATUS_PENDING)->first();
      if($userWithdraw){
          return Response()->json([
              'code'=>0,
              'message'=>'你已经有正在申请的提现记录',
          ]);
      }
      if($request->price > $user->money ){
          return Response()->json(
              [     'code'=>0,
                  'message'=>'余额不足',
                  ]
          );
      }
     $bankResult= getBank($request->bank_code);

      //写入申请表
      $withdraw=  new UserWithdraw();
      $withdraw->price=$request->price;
      $withdraw->user_id=$user->id;
      $withdraw->bank_code=$request->bank_code;
      $withdraw->user_name=$request->user_name;
      $withdraw->bank_type=$bankResult['bank'];
      $withdraw->status=UserWithdraw::STATUS_PENDING;
      $withdraw->save();
      User::where('id',$user->id)->decrement('money',$request->price);
      return Response()->json(
          ['code'=>1,'message'=>'申请提现成功，请等待审核']
      );
    }
    public function withdrawDetail(){
        return view('mobile.myTeam.withdrawDetail');
    }
    public function withdrawAjax(){
        $user=\Auth::user();
        $userWithdraw=  UserWithdraw::where('user_id',$user->id)->orderBy('created_at','desc')->paginate(10);
        return view('mobile.myTeam.withdrawAjax',compact('userWithdraw')) ;
    }
//   提现说明
    public  function tixian(){
        return view('mobile.myTeam.tixian') ;
    }
    /**
     * 个人信息
     */
    public function edit(){
        $user=User::with('team')->where('id',\Auth::id())->first();

        return view('mobile.myTeam.edit',compact('user'));
    }
    /**
     * 我的海报页面
     */
    public function poster(UserInterface $userService){
        $user=\Auth::user();
        $qrcode=$userService->userQrcode($user);

        return view('mobile.myTeam.qrcode',compact('user','qrcode'));
    }

    /**
     * 我的朋友圈
     */
    public function friends(Request $request,UserInterface $userService){
        $this->user=\Auth::user();
        $user=User::with('leader')->where('id',\Auth::id())->first();
        $team=$request->team ?? '';
        $myFriendSecondNumber=$userService->getMyFriendSecondNumber($this->user);
        $myFriendNumber=   $userService->getMyFriendNumber($this->user);
        $myTeamNumber=$userService->getMyTeamNumber($this->user);
        $myTeamCount=$userService->getMyTeamCount($this->user);
        $myTeam=UserTeam::all();
        return view('mobile.myTeam.friends',compact('myFriendNumber','team','myTeam','myTeamCount','myFriendSecondNumber','myTeamNumber','user'));
    }
    public function  levelFriends(Request $request,$level){

        $this->user=\Auth::user();
            $userId=\Auth::user()->id;
            $team=$request->team;
        if($level==1){
            $userList=User::where('team_leader',$this->user->id)->orderBy('created_at','desc');


        }elseif($level==2){
            $userList=User::whereRaw("find_in_set('$userId',team_path) = 3")->orderBy('created_at','desc');
        }else{
            abort(404);
        }
        if($team){
            $userList=$userList->where('team_level_id',$team);
        }

            $userList=$userList->paginate(10);
        return view('mobile.myTeam.ajaxFriend',compact('userList'));
    }

    /**
     * 个人总收益
     */
    public function totalProfit(){
        $user=\Auth::user();
        $distributionMoney=UserMoneyLog::where('leader_id',$user->id)->where('status',0)->where('type',0)->sum('price');
        $teamMoney=UserMoneyLog::where('leader_id',$user->id)->where('status',0)->where('type',1)->sum('price');
        return view('mobile.myTeam.totalProfit',compact('user','distributionMoney','teamMoney'));
    }
    /**
     *
     */
    public function profit(Request $request,$type){
        $user=\Auth::user();
        if($type!='distribution'&&$type!='team')
            abort(404);

            $userMoneyLog=UserMoneyLog::where('leader_id',$user->id);

            if($type=='distribution'){
                $userMoneyLog=$userMoneyLog->where('type',0);
                $totalMoney=$user->distribution_money;
            }elseif ($type=='team'){
                $userMoneyLog=$userMoneyLog->where('type',1);
                $totalMoney=$user->team_money;
            }
            if($request->money&&$request->money=='used'){
                $userMoneyLog=$userMoneyLog->where('status',1);
                $totalMoney=$type=='distribution' ? $user->distribution_used_money :$user->team_used_money;
            }elseif ($request->money&&$request->money=='noUsed'){
                $userMoneyLog=$userMoneyLog->where('status',0);
                $totalMoney=$type=='distribution' ? $user->distribution_money-$user->distribution_used_money : $user->team_money-$user->team_used_money;
            }

        return view('mobile.myTeam.profit',compact('user','type','totalMoney'));
    }
    /**
     *ajaxProfit 获取数据
     */
    public function ajaxProfit(Request $request){
       $user=\Auth::user();
       $type=$request->type;
        if($type!='distribution'&&$type!='team')
            abort(404);
        $userMoneyLog=UserMoneyLog::with(['order','good','user'])->where('leader_id',$user->id);
        if($request->money&&$request->money=='used'){
            $userMoneyLog=$userMoneyLog->where('status',1);
        }elseif ($request->money&&$request->money=='noUsed'){
            $userMoneyLog=$userMoneyLog->where('status',0);
        }
        if($type=='distribution'){
            $userMoneyLog=$userMoneyLog->where('type',0);
        }elseif ($type=='team'){
            $userMoneyLog=$userMoneyLog->where('type',1);
        }
        $userMoneyLog=$userMoneyLog->orderBy('created_at','desc')->paginate(10);

        return view('mobile.myTeam.ajaxProfit',compact('user','userMoneyLog','type'));
    }
}
